package com.sh.common.page;

import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import flexjson.JSONSerializer;

public class PageUtils {

	private static int defaultPageSize = 30; // 默认条数

	/**
	 * 获得工具条（JS的可以参照着写）
	 * 使用隐藏域的方式避免拼凑的计算，还有get、混合get/post会发生过滤器问题
	 */
	public static String getPageBar(HttpServletRequest request, PageBean pageBean){
		// page信息
		int currentPage = pageBean.getCurrentPage();
		int totalPage = pageBean.getTotalPage();
		int totalCount = pageBean.getTotalCount();
		String url = parseURL(request);
		// 拼接字符串
		StringBuilder bar = new StringBuilder();
		bar.append("<form method='post' id='pageform' name='pageform' action='' style='margin-bottom: 0px;'>");
		// 最好不要让form提交地址拼接参数的方式
		bar.append(params2Input(request));
		// 链接
		if(pageBean.hasFirstPage()){
			bar.append("<a href='javascript:ChangePage(1);'>首页</a>&nbsp;");
		}
		if(pageBean.hasPreviousPage()){
			int prePage = currentPage-1;
			// bar.append("<a href='"+url+"&currentPage="+prePage+"'>上一页</a>&nbsp;");
			bar.append("<a href='javascript:ChangePage("+prePage+");'>上一页</a>&nbsp;");
		}
		if(pageBean.hasNextPage()){
			int nextPage = currentPage+1;
			bar.append("<a href='javascript:ChangePage("+nextPage+");'>下一页</a>&nbsp;");
		}
		if(pageBean.hasLastPage()){
			bar.append("<a href='javascript:ChangePage("+totalPage+");'>末页</a>&nbsp;");
		}
		// 页数
		bar.append("当前第"+currentPage+"页&nbsp;&nbsp;");
		bar.append("共"+totalPage+"页&nbsp;&nbsp;");
		bar.append("共"+totalCount+"主题&nbsp;&nbsp;");
		// 跳转
		bar.append("跳转到第");
		bar.append("<select id='currentPage' name='currentPage' onchange='javascript:ChangePage(this.value);' style='margin-bottom: 0px; width=40px'>");
		if(0 == totalPage){
			bar.append("<option value='0' selected>0</option>"); // 0页的时候不为空
		}else if(0 < totalPage){
			for (int i = 1; i <= totalPage; i++) {
				bar.append("<option value='" + i + "'");
				if (currentPage == i) {
					bar.append(" selected");
				}
				bar.append(">"+ i +"</option>");
				bar.append("" + i + "");
			}
		}
		bar.append("</select>页");
		// 脚本
		bar.append("<script language='javascript'>");
		bar.append("function ChangePage(testpage){");
		bar.append("document.pageform.action='" + url +"&currentPage='+testpage;");
		bar.append("document.pageform.submit();");
		bar.append("}");
		bar.append("</script>");
		bar.append("</form>");
		return bar.toString();
	}

	/**
	 * 解析每页记录数（如果以后是传记录数的时候）
	 */
	public static int parsePageSize(HttpServletRequest request){
		String pageSize = request.getParameter("pageSize");
		if (pageSize == null || "".equals(pageSize.trim()))
			return defaultPageSize;
		try {
			return Integer.parseInt(pageSize);
		} catch (Exception e) {
			return defaultPageSize;
		}
	}

	/**
	 * 解析当前页数
	 */
	public static int parseCurrentPage(HttpServletRequest request){
		String currentPage = request.getParameter("currentPage");
		if (currentPage == null || "".equals(currentPage.trim()) || "0".equals(currentPage.trim()))
			return 1;
		try {
			return Integer.parseInt(currentPage);
		} catch (Exception e) {
			return 1;
		}
	}

	/**
	 * 解析请求地址，只留关键参数
	 */
	public static String parseURL(HttpServletRequest request){
		String path = request.getRequestURI(); // 不带参数的路径
		Enumeration paramnames = request.getParameterNames();
		StringBuffer sb = new StringBuffer();
		while (paramnames.hasMoreElements()) {
			String paramname = (String) paramnames.nextElement();
			// 关键的参数
			if (!(paramname.equals("task") || paramname.equals("pageSize")))
				continue;
			String[] paramvalues = request.getParameterValues(paramname);
			if (null != paramvalues) {
				for (int i = 0; i < paramvalues.length; i++) {
					if(!"".equals(paramvalues[i])){
						// 解决参数值带空格问题，回填后浏览器会还原成空格
						paramvalues[i] = paramvalues[i].replace(" " ,"+");
						sb.append("&" + paramname + "=" + paramvalues[i]);
					}
				}
			}
		}
		return path+"?"+sb.toString();
	}

	/**
	 * 得到所有的参数字符串为表单元素字符串
	 * 不用解决参数值带空格问题
	 */
	public static String params2Input(HttpServletRequest request) {
		Enumeration paramNames = request.getParameterNames();
		StringBuffer sb = new StringBuffer();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			// 忽略的参数
			if (paramName.equals("currentPage") || paramName.equals("task") || paramName.equals("pageSize"))
				continue;
			String[] paramValues = request.getParameterValues(paramName);
			if (null != paramValues) {
				for (int i = 0; i < paramValues.length; i++) {
					if(!"".equals(paramValues[i])){
						sb.append("<input type='hidden' name='" + paramName + "' value='" + paramValues[i]+"' />");
					}
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 获得总数
	 */
	public static String getPageCountSql(String sql, String database){
		String db = database.trim().toLowerCase();
		StringBuilder countSql = new StringBuilder(sql.length()+100);
		if(db.equals("oracle") || db.equals("mysql")){
			countSql.append("SELECT COUNT(1) FROM (");
			countSql.append(sql);
			countSql.append(") t_");
		}
		return countSql.toString();
	}

	/**
	 * 获得分页列表语句
	 */
	public static String getPageListSql(String sql, PageBean pageBean, String database){
		String db = database.trim().toLowerCase();
		StringBuilder listSql = new StringBuilder(sql.length()+100);
		if(db.equals("oracle")){
			listSql.append("SELECT * FROM( SELECT t.*, rownum rn FROM (");
			listSql.append(sql);
			listSql.append(") t where rownum <=");
			listSql.append(pageBean.getEndOfPage());
			listSql.append(") t where t.rn >=");
			listSql.append(pageBean.getStartOfPage());
		}else if(db.equals("mysql")){
			listSql.append(sql);
			// 序号从0开始的计数
			listSql.append(" limit "+(pageBean.getStartOfPage()-1)+", "+pageBean.getPageSize());
		}
		return listSql.toString();
	}

	/**
	 * 解析成JSON
	 */
	public static String parseList2Json(List originList){
		String tListJson = new JSONSerializer().exclude("*.class").deepSerialize(originList);
		return tListJson;
	}

	/**
	 * 分页的模板方法（有改进的空间）
	 * PageHelper，可以自定义countSql、listSql、查询方法的实现
	 * 能不能定义也可以，不定义也可以呢？重载方法？
	 */
	public static PageBean searchPage(String sql, Object[] params, int currentPage, int pageSize, PageHelper helper){
		String database = helper.getDataBaseType();
		String countSql = getPageCountSql(sql, database);
		int totalCount = helper.getPageCount(countSql, params);
		PageBean pageBean = new PageBean(totalCount, pageSize, currentPage);
		// 这里能不能再简洁点，最后再new PageBean()
		String listSql = getPageListSql(sql, pageBean, database);
		List<Object> list = helper.getPageList(listSql, params);
		pageBean.setList(list);
		return pageBean;
	}
}
